package dao

import (
	dom "a-common/domain"
	"a-system/domain/entity"
	"strings"
	"sync"
)

var (
	sysNoticeDaoTemp *SysNoticeDao
	sysNoticeDaoOnce sync.Once
)

type SysNoticeDao struct{}

func NewSysNoticeDao() *SysNoticeDao {
	sysNoticeDaoOnce.Do(func() {
		sysNoticeDaoTemp = &SysNoticeDao{}
	})
	return sysNoticeDaoTemp
}

// List 列表
func (m *SysNoticeDao) List(args *entity.SysNoticeDto) (dom.PageVo, error) {
	// 构建查询条件
	query := pgCli.Table(&entity.SysNotice{}).Where("1 = 1")
	if args.NoticeTitle != "" {
		query.And("notice_title LIKE ?", args.NoticeTitle+"%")
	}
	if args.NoticeType != "" {
		query.And("notice_type = ?", args.NoticeType)
	}
	if args.Status != "" {
		query.And("status = ?", args.Status)
	}
	if args.CreatedBy != "" {
		query.And("created_by = ?", args.CreatedBy)
	}
	// 查询
	var vPage dom.PageVo
	var rows []entity.SysNoticePageVo
	total, err := query.Limit(args.PageSize, (args.PageNum-1)*args.PageSize).Asc("notice_id").FindAndCount(&rows)
	if err != nil {
		return vPage, err
	}
	vPage.PageNum = args.PageNum
	vPage.PageSize = args.PageSize
	vPage.Rows = rows
	vPage.Total = total
	return vPage, err
}

// Get 查
func (m *SysNoticeDao) Get(id string) (entity.SysNoticePageVo, error) {
	var v entity.SysNoticePageVo
	_, err := pgCli.Table(&entity.SysNotice{}).ID(id).Get(&v)
	return v, err
}

// Add 增
func (m *SysNoticeDao) Add(args *entity.SysNoticeDto) (int64, error) {
	return pgCli.InsertOne(
		&entity.SysNotice{
			NoticeTitle:   args.NoticeTitle,
			NoticeType:    args.NoticeType,
			NoticeContent: args.NoticeContent,
			Status:        args.Status,
			BaseStruct: dom.BaseStruct{
				CreatedBy: args.CreatedBy,
				UpdatedBy: args.CreatedBy,
				Remark:    args.Remark,
			},
		})
}

// Edit 改
func (m *SysNoticeDao) Edit(args *entity.SysNoticeDto) (int64, error) {
	return pgCli.ID(args.NoticeId).Update(
		&entity.SysNotice{
			NoticeTitle:   args.NoticeTitle,
			NoticeType:    args.NoticeType,
			NoticeContent: args.NoticeContent,
			Status:        args.Status,
			BaseStruct: dom.BaseStruct{
				UpdatedBy: args.UpdatedBy,
				Remark:    args.Remark,
			},
		})
}

// Del 删
func (m *SysNoticeDao) Del(ids string) (int64, error) {
	return pgCli.In("notice_id", strings.Split(ids, `,`)).Delete(&entity.SysNotice{})
}
